package com.wistech.utils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.springframework.util.Assert;

public class DocumentUtils {
	private DocumentUtils() {
	}

	/**
	 * Return a map containing all parameters with the given prefix. Maps single
	 * values to String and multiple values to String array.
	 * <p>
	 * For example, with a prefix of "external_", "external_param1" and
	 * "external_param2" result in a Map with "param1" and "param2" as keys.
	 * 
	 * @param inputDocument
	 *            SolrInputDocument in which to look for parameters
	 * @param prefix
	 *            the beginning of parameter names (if this is null or the empty
	 *            string, all parameters will match)
	 * @return map containing request parameters <b>without the prefix</b>,
	 *         containing either a String or a String array as values
	 */
	public static Map<String, Object> getFieldsStartingWith(
			SolrInputDocument inputDocument, String prefix) {
		Assert.notNull(inputDocument, "Request must not be null");
		Collection<String> paramNames = inputDocument.getFieldNames();
		Map<String, Object> params = new HashMap<String, Object>();
		if (prefix == null) {
			prefix = "";
		}
		for (String paramName : paramNames) {
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				// String unprefixed = paramName.substring(prefix.length());
				SolrInputField inputField = inputDocument.getField(paramName);
				String unprefixed = paramName.substring(prefix.length());
				if (inputField != null) {
					Object value = inputField.getValue();
					if (value != null) {
						params.put(unprefixed, value);
					}
				}
			}
		}
		return params;
	}
}
